<template>
  <div class="banner">
    <div class="wrapper">
      <!-- 背景图 -->
      <img src="../../assets/images/8.png" alt="background">
      <!-- 轮播区域 -->
      <div class="tp">
        <ul class="pic">
          <li v-if="swiperData.length > 0">
            <a href="#">
              <img :src="currentImage" alt="轮播图" style="margin-left: 5px;"/>
            </a>
          </li>
        </ul>
        <ol>
          <li 
            v-for="(item, index) in swiperData" 
            :key="item.id"
            :class="{ current: currentIndex === index }"
            @mouseover="handleIndicatorHover(index)"
          >
            <i></i>
          </li>
        </ol>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'

// 轮播图数据
const swiperData = ref([])
// 当前显示的图片下标
const currentIndex = ref(0)
// 定时器ID
let timer = null

// 计算当前显示的图片URL
const currentImage = computed(() => {
  return swiperData.value[currentIndex.value]?.imgUrl || ''
})

// 处理指示器悬停事件
const handleIndicatorHover = (index) => {
  currentIndex.value = index
  resetTimer()
}

// 获取轮播图数据
const fetchSwiperData = async () => {
  try {
    const response = await fetch('http://127.0.0.1:3000/api/swiper/getAllimg')
    const data = await response.json()
    
    if (data.status === 0) {
      // 过滤state为1的图片
      swiperData.value = data.data.filter(item => item.state === 1)
    }
  } catch (error) {
    console.error('获取轮播图数据失败:', error)
  }
}

// 启动自动轮播
const startAutoPlay = () => {
  timer = setInterval(() => {
    currentIndex.value = (currentIndex.value + 1) % swiperData.value.length
  }, 3000)
}

// 重置定时器
const resetTimer = () => {
  clearInterval(timer)
  startAutoPlay()
}

onMounted(async () => {
  await fetchSwiperData()
  if (swiperData.value.length > 0) {
    startAutoPlay()
  }
})

onUnmounted(() => {
  clearInterval(timer)
})
</script>



<style lang="css" scoped>

/* 轮播区域 */
.banner{
  width: 100%;
  
}
.wrapper{
  position:relative
}
.tp{
  width:72%;
    height: 100%;
position:absolute;top:60px;left:250px;
}

</style>